package srv

import (
	"context"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/asserts"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/auths"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/beans"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/ferror"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/gorms"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/sqls"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/xids"
	"gitee.com/shiqiyue/xd-bi/internal/modules/cr/gqlgen/mgr/gmodel"
	"gitee.com/shiqiyue/xd-bi/internal/modules/cr/model"
	"gorm.io/gorm"
	"time"
)

func DictCategoryInit() {
	srv := &DictCategorySrv{}
	err := beans.ProvideBean(srv)
	asserts.Nil(err, err)
}

type DictCategorySrv struct {
	ReportDbSrv *ReportDbSrv `inject:""`

	Db *gorm.DB `inject:""`
}

func (s *DictCategorySrv) GetByCategoryCode(ctx context.Context, code string) (*model.DictCategory, error) {
	db := gorms.GetDb(ctx, s.Db)
	r := &model.DictCategory{}
	err := db.Model(&model.DictCategory{}).Where(&model.DictCategory{CategoryCode: code}).Take(r).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		return nil, ferror.Wrap("根据编号获取分类异常", err)
	}
	return r, nil

}

func (s DictCategorySrv) GetByCategoryId(ctx context.Context, dictCategoryId string) (*model.DictCategory, error) {
	db := gorms.GetDb(ctx, s.Db)
	r := &model.DictCategory{}
	err := db.Model(&model.DictCategory{}).Where(&model.DictCategory{DictionaryCategoryID: dictCategoryId}).Take(r).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		return nil, err
	}
	return r, nil

}

// 添加分类
func (s *DictCategorySrv) AddCategory(ctx context.Context, code string, name string, categoryType int, remarks *string) error {
	categoryCount, err := s.CountByCategoryCode(ctx, code)
	if err != nil {
		return err
	}
	if categoryCount > 0 {
		return ferror.New("分类已存在")
	}

	db := gorms.GetDb(ctx, s.Db)
	now := time.Now()
	currentUser := auths.GetUser(ctx)
	err = db.Create(&model.DictCategory{
		DictionaryCategoryID: xids.GetXid(ctx),
		CategoryName:         name,
		CategoryCode:         code,
		Remarks:              remarks,
		CreatedAt:            now,
		CreatedBy:            &currentUser.UserId,
		UpdatedAt:            now,
		UpdatedBy:            &currentUser.UserId,
		CategoryType:         &categoryType,
	}).Error
	if err != nil {
		return ferror.Wrap("保存分类失败", err)
	}
	return nil
}

func (s DictCategorySrv) CountByCategoryCode(ctx context.Context, code string) (int64, error) {
	db := gorms.GetDb(ctx, s.Db)
	var c int64
	err := db.Model(&model.DictCategory{}).Where(&model.DictCategory{CategoryCode: code}).Count(&c).Error
	if err != nil {
		return 0, ferror.WrapCode("获取数量异常", err)
	}
	return c, nil
}

func (s DictCategorySrv) CountByCategoryCodeAndNeqCategoryId(ctx context.Context, code, categoryId string) (int64, error) {
	db := gorms.GetDb(ctx, s.Db)
	var c int64
	err := db.Model(&model.DictCategory{}).Where("dictionary_category_id != ? and category_code = ?", categoryId, code).Count(&c).Error
	if err != nil {
		return 0, ferror.WrapCode("获取数量异常", err)
	}
	return c, nil
}

// 修改分类
func (s *DictCategorySrv) EditCategory(ctx context.Context, categoryId string, code string, name string, remarks *string) error {
	categoryCount, err := s.CountByCategoryCodeAndNeqCategoryId(ctx, code, categoryId)
	if err != nil {
		return err
	}
	if categoryCount > 0 {
		return ferror.New("分类已存在")
	}
	db := gorms.GetDb(ctx, s.Db)
	now := time.Now()
	currentUser := auths.GetUser(ctx)
	category, err := s.GetByCategoryId(ctx, categoryId)
	if err != nil {
		return ferror.Wrap("获取分类异常", err)
	}
	if category == nil {
		return ferror.New("分类不存在")
	}
	category.CategoryName = name
	category.CategoryCode = code
	category.Remarks = remarks
	category.UpdatedAt = now
	category.UpdatedBy = &currentUser.UserId
	err = db.Save(category).Error
	if err != nil {
		return ferror.Wrap("保存失败", err)
	}
	return nil

}

// 删除分类
func (s *DictCategorySrv) DeleteCategory(ctx context.Context, categoryId string) error {
	db := gorms.GetDb(ctx, s.Db)
	err := db.Model(&model.DictCategory{}).Where(&model.DictCategory{DictionaryCategoryID: categoryId}).Delete(nil).Error
	if err != nil {
		return ferror.Wrap("删除失败", err)
	}
	return nil
}

func (s *DictCategorySrv) Page(ctx context.Context, req gmodel.DictCategoryPageReq) ([]*model.DictCategory, int, error) {
	db := gorms.GetDb(ctx, s.Db)
	queryParam := make(map[string]interface{}, 0)
	if req.CategoryCode != nil && *req.CategoryCode != "" {
		queryParam["CategoryCode"] = *req.CategoryCode
	}
	if req.CategoryName != nil && *req.CategoryName != "" {
		queryParam["CategoryName"] = *req.CategoryName
	}
	if req.OrderColumn != nil && *req.OrderColumn != "" {
		if *req.OrderBy == "descending" {
			queryParam["OrderByDirection"] = "desc"
		} else {
			queryParam["OrderByDirection"] = "asc"
		}
		switch *req.OrderColumn {
		case "CategoryName":
			queryParam["OrderByColumn"] = "category_name"
		case "CategoryCode":
			queryParam["OrderByColumn"] = "category_code"
		case "CategoryType":
			queryParam["OrderByColumn"] = "category_type"
		case "CreatedAt":
			queryParam["OrderByColumn"] = "created_at"
		case "UpdatedAt":
			queryParam["OrderByColumn"] = "updated_at"
		}
	} else {
		queryParam["OrderByColumn"] = "id"
		queryParam["OrderByDirection"] = "desc"
	}
	var c int
	rs := make([]*model.DictCategory, 0)
	err := sqls.Page(ctx, db, sqls.PageParam{
		ListSql:     &DictCategoryPageSql,
		CountSql:    &DictCategoryCountSql,
		M:           queryParam,
		CurrentPage: req.CurrentPage,
		PageSize:    req.PageSize,
	}, &c, &rs)
	if err != nil {
		return nil, 0, err
	}
	return rs, c, nil
}

func (s DictCategorySrv) ListAll(ctx context.Context) ([]*model.DictCategory, error) {
	db := gorms.GetDb(ctx, s.Db)
	rs := make([]*model.DictCategory, 0)
	err := db.Model(&model.DictCategory{}).Find(&rs).Error
	if err != nil {
		return nil, err
	}
	return rs, nil
}
